package com.zhang.novel.service.impl;

import com.zhang.novel.core.cache.CacheKey;
import com.zhang.novel.core.cache.CacheService;
import com.zhang.novel.entity.FriendLink;
import com.zhang.novel.mapper.FriendLinkMapper;
import com.zhang.novel.service.FriendLinkService;
import lombok.RequiredArgsConstructor;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.zhang.novel.mapper.FriendLinkDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.select.SelectDSL.select;

@Service
@RequiredArgsConstructor
public class FriendLinkServiceImpl implements FriendLinkService {

    private final FriendLinkMapper friendLinkMapper;

    private final CacheService cacheService;

    @Override
    public List<FriendLink> listIndexLink() {
        // 先从缓存获取数据
        List<FriendLink> result = (List<FriendLink>) cacheService.getObject(CacheKey.INDEX_LINK_KEY);

        if (null == result || result.size() == 0) {
            SelectStatementProvider selectStatementProvider = select(linkName, linkUrl)
                    .from(friendLink)
                    .where(isOpen, isEqualTo((byte) 1))
                    .orderBy(sort)
                    .build()
                    .render(RenderingStrategies.MYBATIS3);
            result = friendLinkMapper.selectMany(selectStatementProvider);
            cacheService.setObject(CacheKey.INDEX_LINK_KEY, result, 60 * 60 * 24);
        }
        return result;
    }
}
